package com.qin.dao;

import java.sql.SQLException;
import java.util.List;

import com.qin.entity.User;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.handler.BeanHandler;

/**
 * 操作user类
 * @author BestRiven
 *
 */
public class UserDao {
	
	/**
	 * 插入用户
	 * @param user 要添加的用户
	 * @return 自增id
	 */
	public Long insertUser(User user) {
		Entity record = Entity.parseWithUnderlineCase(user);
		Long insertForGeneratedKey = 0L;
		try {
			insertForGeneratedKey = Db.use().insertForGeneratedKey(record);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return insertForGeneratedKey;
	}
	
	/**
	 * 逻辑删除用户
	 * @param id 用户的id
	 * @return 影响行数
	 */
	public int logincDeleteUser(Long id) {
		String sql = "UPDATE `user` SET `status` = 0 WHERE `id` = ?";
		int execute = 0;
		try {
			execute = Db.use().execute(sql, id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return execute;
	}
	
	/**
	 * 修改用户
	 * @param id 要修改用户的id
	 * @param user 要修改的信息
	 * @return 影响行数
	 */
	public int updateUser(Long id, User user) {
		Entity record = Entity.parseWithUnderlineCase(user);
		Entity where = Entity.create("user").set("id", id);
		
		int update = 0;
		try {
			update = Db.use().update(record, where);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return update;
	}
	
	/**
	 * 查询当前user
	 * @param id 要查询用户的id
	 * @return 查询到的用户
	 */
	public User queryUser(Long id) {
		Entity where = Entity.create("user").set("id", id);
		User find = null;
		try {
			find = Db.use().find(where,new BeanHandler<User>(User.class));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return find;
	}
	
	/**
	 * 通过字符串查询用户
	 * @param str 用户名或者邮箱
	 * @param isEmail 判断是否是邮箱
	 * @return 查询到的用户
	 */
	public User queryUser(String str,Boolean isEmail) {
		Entity where = Entity.create("user");
		if(isEmail) { // 是邮箱
			where.set("email", str);
		}else {	// 是用户名
			where.set("name", str);
		}
		User find = null;
		try {
			find = Db.use().find(where,new BeanHandler<User>(User.class));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return find;
	}
	
	/**
	 * 查询所有的用户
	 * @return
	 */
	public List<User> querryAllUsers(){
		List<User> find = null;
		try {
			find = Db.use().find(Entity.create("user"),User.class);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return find;
	}
}
